package com.boruan.shengtangfeng.core.service.impl;

import java.util.Date;
import java.util.List;

import cn.jpush.api.schedule.model.IModel;
import com.boruan.shengtangfeng.core.dao.IModuleVideoDao;
import com.boruan.shengtangfeng.core.entity.ModuleVideo;
import com.boruan.shengtangfeng.core.vo.QuestionVo;
import com.boruan.shengtangfeng.core.vo.mapper.QuestionVoMapper;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.beetl.sql.core.db.KeyHolder;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.boruan.shengtangfeng.core.dao.IModuleDao;
import com.boruan.shengtangfeng.core.dao.IModuleQuestionDao;
import com.boruan.shengtangfeng.core.dao.IQuestionRecordDao;
import com.boruan.shengtangfeng.core.entity.Module;
import com.boruan.shengtangfeng.core.entity.ModuleQuestion;
import com.boruan.shengtangfeng.core.entity.QuestionRecord;
import com.boruan.shengtangfeng.core.service.IModuleService;
import com.boruan.shengtangfeng.core.utils.GlobalReponse;
import com.boruan.shengtangfeng.core.vo.ModuleVo;
import com.boruan.shengtangfeng.core.vo.mapper.ModuleVoMapper;

/**
 * @author: 刘光强
 * @Description: 配置管理
 * @date:2020年3月10日 上午11:14:10
 */
@Service
@Transactional(readOnly = true)
public class ModuleService implements IModuleService {
	@Autowired
	private IModuleDao moduleDao;
	@Autowired
	private IQuestionRecordDao questionRecordDao;
    @Autowired
    private IModuleQuestionDao moduleQuestionDao;
    @Autowired
    private IModuleVideoDao moduleVideoDao;
	/**
	 * @author: 刘光强
	 * @Description: 分页获取
	 * @date:2020年3月10日 上午11:14:10
	 */
	@Override
	public void pageQuery(PageQuery<Module> pageQuery, Module module) {
		pageQuery.setParas(module);
		moduleDao.pageQuery(pageQuery);
	}



    /**
	 * @author: 刘光强
	 * @Description: 详情
	 * @date:2020年3月10日 上午11:14:10
	 */
	@Override
	public Module findById(Long id) {
		return moduleDao.unique(id);
	}

    @Override
    public ModuleQuestion findByModuleId(ModuleQuestion moduleQuestion) {
        return moduleQuestionDao.findByModuleId(moduleQuestion);
    }
	/**
	 * @author: 刘光强
	 * @Description: 添加修改
	 * @date:2020年3月10日 上午11:14:10
	 */
	@Override
	@Transactional(readOnly = false)
	public void save(Module module) {
		if (module.getId() == null) {
			KeyHolder kh = moduleDao.insertReturnKey(module);
			module.setId(kh.getLong());
		} else {
			moduleDao.updateById(module);
		}
	}
    @Override
    @Transactional(readOnly = false)
    public void saveQuestion(ModuleQuestion moduleQuestion) {
            moduleQuestionDao.update(moduleQuestion);

    }

    @Override
    public List<ModuleVo> findTree(Long userId) {
        Module search=new Module();
        search.setIsDeleted(false);
        search.setParentId(0L);
        List<Module> list=moduleDao.template(search);
        List<ModuleVo> vos=ModuleVoMapper.MAPPER.toVo(list);
        vos.forEach(vo->{
            //用户做题数量
            QuestionRecord searchRecord=new QuestionRecord();
            searchRecord.setObjectId(vo.getId());
            searchRecord.setSource(1);
            searchRecord.setUserId(userId);
            Long count=questionRecordDao.templateCount(searchRecord);
            vo.setAnswerCount(count);
        });

        processModuleTree(vos,userId);
        return vos;
    }
    private void processModuleTree(List<ModuleVo> vos,Long userId) {
        if(vos==null||vos.isEmpty()) return;
        vos.forEach(vo->{
            Module search=new Module();
            search.setParentId(vo.getId());
            search.setIsDeleted(false);
            List<Module> list=moduleDao.template(search);
            List<ModuleVo> tempvos=ModuleVoMapper.MAPPER.toVo(list);
            //用户做题数量
            tempvos.forEach(childVo->{
                QuestionRecord searchRecord=new QuestionRecord();
                searchRecord.setObjectId(childVo.getId());
                searchRecord.setSource(1);
                searchRecord.setUserId(userId);
                Long count=questionRecordDao.templateCount(searchRecord);
                childVo.setAnswerCount(count);
                vo.setAnswerCount(vo.getAnswerCount()+childVo.getAnswerCount());
                vo.setQuestionCount(vo.getQuestionCount()+childVo.getQuestionCount());
            });
            vo.setChilds(tempvos);
            processModuleTree(tempvos,userId);
        });
    }

    @Override
    public List<ModuleVo> findModuleTree(Module module) {
        module.setParentId(0L);
        module.setIsDeleted(false);
        List<Module> list = moduleDao.findIdByCondition(module);
        List<ModuleVo> vos = ModuleVoMapper.MAPPER.toVo(list);
        processModuleTree(vos);
        return vos;
    }

    private void processModuleTree(List<ModuleVo> vos) {
        if (vos == null || vos.isEmpty()) return;
        vos.forEach(vo -> {
            Module search = new Module();
            search.setParentId(vo.getId());
            List<Module> list = moduleDao.findIdByCondition(search);
            List<ModuleVo> tempvos = ModuleVoMapper.MAPPER.toVo(list);
            vo.setChilds(tempvos);
            processModuleTree(tempvos);
        });
    }
    @Override
    public Integer getMaxSequence(Module search) {
        return moduleDao.getMaxSequence(search);
    }
    @Override
    public Module templateOne(Module search) {
        return moduleDao.templateOne(search);
    }



    @Override
    public List<Module> findByCondition(Module module) {
        return moduleDao.findIdByCondition(module);
    }

    @Override
    public List<Module> findByCondition1(Module search) {
        return moduleDao.findIdByCondition1(search);
    }

    /**
     * 章节内添加试题
     * @param userId
     * @param moduleId
     * @param questionIdList
     */
    @Override
    @Transactional(readOnly = false)
    public void addQuestions(Long userId, Long moduleId, List<Long> questionIdList) {
        for(Long questionId : questionIdList){
            ModuleQuestion moduleQuestion=new ModuleQuestion();
            moduleQuestion.setModuleId(moduleId);
            moduleQuestion.setQuestionId(questionId);
            Integer maxSequence = moduleQuestionDao.getMaxSequenceC(moduleId);
            if (maxSequence == null) {
                maxSequence = 0;
            }
            moduleQuestion.setSort(maxSequence + 1);
            moduleQuestionDao.insert(moduleQuestion);
        }
        Module module = findById(moduleId);
        module.setUpdateBy(userId.toString());
        module.setUpdateTime(new Date());
        if(module.getQuestionCount()==null){
            module.setQuestionCount(0L);
        }
        Long questionCount=module.getQuestionCount();
        questionCount=questionCount + questionIdList.size();
        module.setQuestionCount(questionCount);
        moduleDao.updateById(module);


    }

    /**
     * 移除章节内的试题
     * @param moduleId
     * @param moduleId
     * @param questionIdList
     */
    @Override
    @Transactional(readOnly = false)
    public void removeQuestions(Long userId,Long moduleId, List<Long> questionIdList) {
        Module module = findById(moduleId);
        module.setUpdateBy(userId.toString());
        module.setUpdateTime(new Date());
        Long questionCount=module.getQuestionCount();
        questionCount=questionCount - questionIdList.size();
        module.setQuestionCount(questionCount);
        moduleDao.updateById(module);
        moduleQuestionDao.deleteByQuestionAndModuleId(moduleId, questionIdList);
    }


    @Override
    @Transactional(readOnly = false)
    public GlobalReponse importFormAnother(Long userId, Long currentId, Long sourceId) {

        //userId用来加日志吧。。。。。。。。。。。。。。。。。。AOP。。。。。。。。。。。。。。。。。。。。。。。。。。。。

        List<Long> sourceQuestionIds = moduleQuestionDao.getSQLManager().execute(new SQLReady("select question_id from module_question where module_id = ?", sourceId), Long.class);

        //成功条数
        int successCount = 0;
        //失败条数
        int failCount = 0;

        //循环插入
        for (Long questionId : sourceQuestionIds) {
            try {
                ModuleQuestion po = new ModuleQuestion();
                po.setModuleId(currentId);
                po.setQuestionId(questionId);
                moduleQuestionDao.insert(po);
                successCount += 1;
            } catch (Exception e) {
                failCount += 1;
            }
        }

        return GlobalReponse.success().setData(successCount).setData1(failCount);
    }

    /**
     * 视频绑定到章节模块
     * @param id
     * @param moduleId
     * @param videoIdList
     */
    @Override
    @Transactional(readOnly = false)
    public void addVideos(Long id, Long moduleId, List<Long> videoIdList) {
        for(Long vId : videoIdList){
            ModuleVideo moduleVideo = moduleVideoDao.single(vId);
            moduleVideo.setModuleId(moduleId);
            moduleVideoDao.updateById(moduleVideo);
            Module module = moduleDao.single(moduleId);
            module.setQuestionCount(module.getQuestionCount()+1);
            moduleDao.updateById(module);
        }
    }

    @Override
    @Transactional(readOnly = false)
    public void removeVideos(Long id, Long moduleId, List<Long> videoIdList) {
        for(Long vId : videoIdList){
            ModuleVideo moduleVideo = moduleVideoDao.single(vId);
            moduleVideo.setModuleId(0L);
            moduleVideoDao.updateById(moduleVideo);
            Module module = moduleDao.single(moduleId);
            module.setQuestionCount(module.getQuestionCount()-1);
            moduleDao.updateById(module);
        }
    }


    @Override
    public Module findNext(Long moduleId) {
        Module old=moduleDao.single(moduleId);
        
        Long rownum= moduleDao.findRowNum(old.getParentId(), moduleId);
        Module module = moduleDao.findNext(old.getParentId(), rownum);
        if(module==null) {
            module=moduleDao.findFirst(old.getParentId());
        }
        return module;
    }

    @Override
    public List<Module> findByQuestion(Long questionId) {
        return moduleDao.findByQuestion(questionId);
    }
    

}
